package com.jrx.anytxn.param.job.xib;

import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.BtBatchStatus;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtBtBatchStatusMapper;
import com.jrx.anytxn.param.mapper.ext.ExtScheduleMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Objects;

/**
 * 检查日终（日切）调度跑批是否完成
 *
 * @author : liuzb
 * 2021/09/29
 */
@Configuration
@EnableBatchProcessing
public class CheckCutoverFinishedConfiguration {

    private static final Logger logger = LoggerFactory.getLogger(CheckCutoverFinishedConfiguration.class);

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;
    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    public ExtScheduleMapper extScheduleMapper;
    @Resource
    private ExtBtBatchStatusMapper extBtBatchStatusMapper;

    @Bean
    public Job checkCutoverFinishedJob() {
        return jobBuilderFactory.get("checkCutoverFinishedJob")
                .incrementer(new RunIdIncrementer())
                .start(checkCutoverFinishedStep())
                .build();
    }

    @Bean
    public Step checkCutoverFinishedStep() {
        return stepBuilderFactory.get("checkCutoverFinishedStep").tasklet(checkCutoverFinishedTasklet()).build();
    }

    @Bean
    public Tasklet checkCutoverFinishedTasklet() {
        return (stepContribution, chunkContext) -> {
            // 日终检查次数
            int i = 0;
            // 日终检结果
            boolean fileExistsFlag = false;
            while (!fileExistsFlag) {
                // 查询调度接口
                PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(Constant.DEFAULT_ORG_NUMBER);
                // 获取当前系统日期
                String today = DateUtils.format(org.getToday(), "yyyy-MM-dd");
                logger.info("检查调度是否完成today:{}，时间为:{}", today, DateUtils.formatDateTime(new Date()));
                BtBatchStatus batchStatus = extBtBatchStatusMapper.selectByStatusAndJobName(Constant.BATCH_SATTUS_2, Constant.ABLE_TO_REPORT, org.getTenantId(), org.getToday());
                if (Objects.isNull(batchStatus)) {
                    Thread.sleep(1000 * 60 * 5);
                } else {
                    fileExistsFlag = true;
                }
                logger.info("检查日切任务是否调成功调用完成,第{}次查询，校验结果：{}", i + 1, fileExistsFlag);
                i++;
            }
            return RepeatStatus.FINISHED;
        };
    }

}